/**
 * 
 */
package org.wmine.visualization.eventhandlers;

import java.awt.ItemSelectable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.xml.parsers.ParserConfigurationException;

import org.wmine.core.MainWindow;
import org.wmine.core.ProjectManager;
import org.wmine.visualization.DrawFrequencyDistributionGraph;
import org.wmine.visualization.DrawLinearRegressionGraph;
import org.wmine.visualization.IDrawMiningAlgorithmOutput;
import org.wmine.visualization.SetChartPanel;
 
import org.wmine.visualization.data.AbstractChartDataProvider;
import org.wmine.visualization.data.FrequencyDistributionData;
import org.wmine.visualization.data.FrequencyDistributionDataProvider;
import org.wmine.visualization.data.KMeansData;
import org.wmine.visualization.data.KMeansDataProvider;
import org.wmine.visualization.data.LinearRegData;
import org.wmine.visualization.data.LinearRegDataProvider;
import org.wmine.visualization.data.FrequencyDistributionData.FreqDistDataSingleClass;
import org.wmine.visualization.data.LinearRegData.LinearRegSingleData;
import org.wmine.visualization.eventhandlers.DisplayGraphEventHandler;
import org.wmine.visualization.ui.AttributeSelectionWindow;
 
import org.xml.sax.SAXException;

import com.sun.org.apache.bcel.internal.generic.LMUL;

/**
 * @author Rajeev Kumar Thakur
 *	this class handles the events by combobox for algorithm
 */

public class ComboAlgoEventHandler implements ItemListener{
	
	private AbstractChartDataProvider chartData;
	private FrequencyDistributionData frqData;
	private ArrayList<FreqDistDataSingleClass> classList;
	private LinearRegData regressionData;
	private ArrayList<LinearRegSingleData> regList;
	
	private String selectedVisualizeMethod;
	private DisplayGraphEventHandler displayButtonHandler;
	private JPanel freqDistPanel;
	private JPanel regressionPanel;
	private JPanel kMeansPanel;
	private JPanel inputPreprocessedFIlePanel;
	private JPanel basePanel;
	private JFrame attrSelectWindow;
	private AttributeSelectionWindow attrSelectWindowObject;
//	private XmlLinearRegReader reader;
	//private ArrayList<RegressionResult> regOutputData;
	private String attribute1Values[];	
	private String attribute2Values[];
	private JComboBox comboAttribute1;
	private JComboBox comboAttribute2;
	private JLabel selectAttribute1Label;
	private JLabel selectAttribute2Label;
	//private IDrawMiningAlgorithmOutput drawMiningOutput1;
	private IDrawMiningAlgorithmOutput drawMiningOutput;
	private SetChartPanel freqGraph;
	private SetChartPanel linRegGraph;
//	private LinRegCalcValues calculateRegValues;
//	XmlFreqDistReader freqReader;
	private static String frqOutputFile = "Freq-Dist.xml";
	private static String regOutputFile = "stat-result.xml";
	private static String kMeansOutputFile = "KmeansOp.xml";
	private ComboAlgoEventHandler comboAlgoEventHandler;
	private ArrayList<String> sctrPlotAttribList;
	
	public ComboAlgoEventHandler(DisplayGraphEventHandler handler, JPanel basePanel) throws ParserConfigurationException, SAXException, IOException {
			displayButtonHandler = handler;
			this.basePanel= basePanel;
			comboAlgoEventHandler = this;
			//displayButtonHandler.setFreqGraph(freqGraph);
	    	//System.out.println("in in combo event handler");
	    	
			comboAttribute1 = new JComboBox();
			comboAttribute2 = new  JComboBox();
			freqDistPanel = new JPanel();
			regressionPanel = new JPanel();
		 
			if(ProjectManager.getUniqueInstance().isProjectOpened()){
				chartData = new LinearRegDataProvider(regOutputFile);
				regressionData = (LinearRegData) chartData.getChartData();
				regList = regressionData.getLinearRegDataList();

			//	chartData = new FrequencyDistributionDataProvider(frqOutputFile);;
			//	frqData =(FrequencyDistributionData) chartData.getChartData();
			//	classList = new ArrayList<FreqDistDataSingleClass>();
			//	classList = frqData.getClassList();

				loadAttributeValues(regList);
				addItemsAttrib1(comboAttribute1);
			}

	}

	public void itemStateChanged(ItemEvent e) {
		// TODO Auto-generated method stub
		 
			selectedVisualizeMethod = e.getItem().toString();
			MainWindow.getInstance().showOnStatusBar(selectedVisualizeMethod);
			displayButtonHandler.setSelectedComboItem(selectedVisualizeMethod);
			
			//System.out.println(selectedComboItem);
			if (selectedVisualizeMethod.equals("Frequency Dist")) {
				if(kMeansPanel !=null)
					basePanel.remove(kMeansPanel);
				if(regressionPanel != null)
					basePanel.remove(regressionPanel);
				if(freqDistPanel != null)
					basePanel.remove(freqDistPanel);
				if(inputPreprocessedFIlePanel != null)
					basePanel.remove(inputPreprocessedFIlePanel);
			
				//kMeansPanel.setVisible(false);
				//regressionPanel.setVisible(false);
				
 				addFreqDistPanel();					
			}
			else
			if (selectedVisualizeMethod.equals("Linear Regression")) {
				try {
					if(kMeansPanel !=null)
						basePanel.remove(kMeansPanel);
					if(freqDistPanel != null)
						basePanel.remove(freqDistPanel);
					if(regressionPanel != null)
						basePanel.remove(regressionPanel);
					if(inputPreprocessedFIlePanel != null)
						basePanel.remove(inputPreprocessedFIlePanel);
				
				//	kMeansPanel.setVisible(false);
					//freqDistPanel.setVisible(false);
					
					addRegressionPanel();
					
				} catch (ParserConfigurationException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (SAXException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}	
			}
			else
				if(selectedVisualizeMethod.equals("KMeans Clustering")){
					//regressionPanel.setVisible(false);
					//freqDistPanel.setVisible(false);
					if(kMeansPanel !=null)
						basePanel.remove(kMeansPanel);
					if(regressionPanel != null)
						basePanel.remove(regressionPanel);
					if(freqDistPanel != null)
						basePanel.remove(freqDistPanel);
					if(inputPreprocessedFIlePanel != null)
						basePanel.remove(inputPreprocessedFIlePanel);
				
					addKMeansPanel();
				}
				else
					if(selectedVisualizeMethod.equals("Scatter Plot")){
						//regressionPanel.setVisible(false);
						//freqDistPanel.setVisible(false);
						if(kMeansPanel !=null)
							basePanel.remove(kMeansPanel);
						if(regressionPanel != null)
							basePanel.remove(regressionPanel);
						if(freqDistPanel != null)
							basePanel.remove(freqDistPanel);
						if(inputPreprocessedFIlePanel != null)
							basePanel.remove(inputPreprocessedFIlePanel);
					
						addInputPreprocessPanel();
					}
					else
						if(selectedVisualizeMethod.equals("Bar Chart")){
							//regressionPanel.setVisible(false);
							//freqDistPanel.setVisible(false);
							if(kMeansPanel !=null)
								basePanel.remove(kMeansPanel);
							if(regressionPanel != null)
								basePanel.remove(regressionPanel);
							if(freqDistPanel != null)
								basePanel.remove(freqDistPanel);
							if(inputPreprocessedFIlePanel != null)
								basePanel.remove(inputPreprocessedFIlePanel);
						
							addInputPreprocessPanel();
						}
						else
							if(selectedVisualizeMethod.equals("Pie Chart")){
								//regressionPanel.setVisible(false);
								//freqDistPanel.setVisible(false);
								if(kMeansPanel !=null)
									basePanel.remove(kMeansPanel);
								if(regressionPanel != null)
									basePanel.remove(regressionPanel);
								if(freqDistPanel != null)
									basePanel.remove(freqDistPanel);
								if(inputPreprocessedFIlePanel != null)
									basePanel.remove(inputPreprocessedFIlePanel);
							
								//addPieChartPanel();
							}
			 
		 
		}
		 /* 
		  * Adds panel for accepting input parameters as preprocessed file 
		  */
	private void addInputPreprocessPanel() {
		// TODO Auto-generated method stub
		inputPreprocessedFIlePanel = new JPanel();
		
		JLabel selectLabel = new JLabel("Select Preprocesed File :");
		selectLabel.setBounds(20, 20, 150,20);
		inputPreprocessedFIlePanel.add(selectLabel);
		
		JComboBox comboFileInput=new JComboBox();
		
		comboFileInput.addItem(new String(" --select-- "));
		if(ProjectManager.getUniqueInstance().isProjectOpened())
		{	String []list=ProjectManager.getUniqueInstance().getFileNamesArray("preprocess");
			for(int i=0;i<list.length;i++)
				comboFileInput.addItem(list[i]);
		}
		
		
		comboFileInput.addItemListener(new ItemListener(){

			public void itemStateChanged(ItemEvent e) {
				// TODO Auto-generated method stub
				
				String fileName = e.getItem().toString();
				//System.out.println("in attribute Selection EventHandler :"+fileName);
				if (!fileName.equals(" --select-- ")) {
					
					if (attrSelectWindow !=null) {
						attrSelectWindow.dispose();
					}
					attrSelectWindowObject = new AttributeSelectionWindow(selectedVisualizeMethod, fileName, displayButtonHandler);
					attrSelectWindow = attrSelectWindowObject.getAttribSelectionWindow(); 
					//attrSelectWindow.setBounds(300,200,300,250);
					attrSelectWindow.setVisible(true);
				}
				
			}
			
		});
		
		comboFileInput.setEditable(false);
		comboFileInput.setBounds(20,50,150,20);	
		inputPreprocessedFIlePanel.add(comboFileInput);
		//if (sctrPlotAttribList != null) {
			
		//	ArrayList<String> temp = sctrPlotAttribList;
	//		String str ="<html>You have Selected Attributes As : <br> For X- Axis :"+temp.get(0)+" For Y- Axis :"+temp.get(1); 
	//		JLabel selectedAttrLabel = new JLabel(str);
		//	selectedAttrLabel.setBounds(20,80,180,40);
			//scatterPanel.add(selectedAttrLabel);
			//scatterPanel.repaint();
			//scatterPanel.validate();
			//basePanel.repaint();
			//basePanel.validate();

		//}
		inputPreprocessedFIlePanel.setLayout(null);
			//scatterPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Input Parameters"));
		inputPreprocessedFIlePanel.setBounds(20,180,180,150);
		basePanel.add(inputPreprocessedFIlePanel);
		}

	private void addKMeansPanel() {
		// TODO Auto-generated method stub
		JLabel inputFileLabel = new JLabel("Select the file for KMeans ");
		inputFileLabel.setBounds(20,20,150,20);
		
		JComboBox fileCombo = new JComboBox();
		fileCombo.addItem(" --- Select --- ");
		fileCombo.addItem(kMeansOutputFile);
		fileCombo.setBounds(20,50,150,20);
		
		kMeansPanel = new JPanel();
		kMeansPanel.setLayout(null);
	//	kMeansPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Input Paremeters"));
		kMeansPanel.setBounds(20,180,180,150);
		kMeansPanel.add(inputFileLabel);
		kMeansPanel.add(fileCombo);
		kMeansPanel.setVisible(true);
		
		fileCombo.addItemListener(new ItemListener() {

			public void itemStateChanged(ItemEvent e) {
				// TODO Auto-generated method stub
				String opFile = e.getItem().toString();
				displayButtonHandler.setKmeansOpFile(opFile);
			}
			
		});
		basePanel.add(kMeansPanel);
	}

	public void addFreqDistPanel() {
		// TODO Auto-generated method stub
		 
		//regressionPanel.setVisible(false);
		//handler.setFreqReader(freqReader);
	
		
	 	JLabel freqDistDetLabel = new JLabel("Frequency distribution");
		freqDistDetLabel.setBounds(20,20,150,20);
		
		JComboBox fileCombo = new JComboBox();
		fileCombo.addItem(" --- Select --- ");
		fileCombo.addItem(frqOutputFile);
		fileCombo.setBounds(20,50,150,20);
	
		fileCombo.addItemListener(new ItemListener() {

			public void itemStateChanged(ItemEvent e) {
				// TODO Auto-generated method stub
				displayButtonHandler.setFrqOutputFile(e.getItem().toString());
			}
			
		});
		freqDistPanel.setLayout(null);
		//freqDistPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Input Paremeters"));
		freqDistPanel.setBounds(20,180,180,150);
		freqDistPanel.add(freqDistDetLabel);
		freqDistPanel.add(fileCombo);
		
		freqDistPanel.setVisible(true);
		basePanel.add(freqDistPanel);
	}
 
	private void addRegressionPanel() throws ParserConfigurationException, SAXException, IOException {
					
		selectAttribute1Label = new JLabel("Select the attributes :");
		selectAttribute1Label.setBounds(20,20,150,20); 
		
		comboAttribute1.setBounds(20,50,150,20);
			
		
		regressionPanel.setLayout(null);
	//	regressionPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Input Paremeters"));
		regressionPanel.setBounds(20,180,180,150);
		regressionPanel.add(selectAttribute1Label);
		regressionPanel.add(comboAttribute1);
		
		comboAttribute1.addItemListener(new ItemListener(){

			public void itemStateChanged(ItemEvent e) {
				// TODO Auto-generated method stub
				String selectedAttributes = new String();
				String attribute1[] =  new String[10];
				selectedAttributes = e.getItem().toString();
				attribute1 = getAssociatesAttribute(selectedAttributes);
				//	System.out.println(attribute1[0].toString());
			
				
				//System.out.println(selectedAttributes);
					if(attribute1[0].toString().equals("----Select----")){
						displayButtonHandler.setLinearRegInputAttribs(attribute1[0].trim(), null);
					}
					else
						displayButtonHandler.setLinearRegInputAttribs(attribute1[0].trim(),attribute1[1].trim());
					
					SetChartPanel freqPanel, linPanel;
					freqPanel = displayButtonHandler.getFreqGraph();
					linPanel = displayButtonHandler.getLinRegGraph();
					if(freqPanel!= null && linPanel != null && kMeansPanel!=null){
						freqPanel.validate();
						freqPanel.repaint();
						linPanel.validate();
						linPanel.repaint();
						kMeansPanel.validate();
						kMeansPanel.repaint();
					}
					 
				} 
			}
			);
		
		
		regressionPanel.setVisible(true);
		freqDistPanel.setVisible(false);
		basePanel.add(regressionPanel);			
	}	
	
	private String[] getAssociatesAttribute(String selectedAttributes) {
		// TODO Auto-generated method stub
		StringTokenizer stringTemp = new StringTokenizer(selectedAttributes,"::");
		String[] asociatedAttributes = new String[4];
		int i = 0;
		while(stringTemp.hasMoreTokens()){
			asociatedAttributes[i] = stringTemp.nextToken();
			//System.out.println(asociatedAttributes[i]);
			i++;
		}	
		return asociatedAttributes;
	}
	
	private void loadAttributeValues(ArrayList<LinearRegSingleData> regOutputData) {
		// TODO Auto-generated method stub
			attribute1Values = new String[regOutputData.size()];
			attribute2Values = new String[regOutputData.size()];
			System.out.println("Size is " +regOutputData.size());
		for (int i = 0; i < regOutputData.size(); i++) {
			LinearRegSingleData temp = regOutputData.get(i);
			attribute1Values[i] = temp.getAttribute1();
			attribute2Values[i] = temp.getAttribute2();		
		//	System.out.println(attribute1Values[i]+" "+attribute2Values[i]);
			}
	} 	
	
		 

		private void addItemsAttrib1(JComboBox comboAttribute1) {
			// TODO Auto-generated method stub
			comboAttribute1.addItem("----Select----");
			for (int i = 0; i < regList.size(); i++) {
				comboAttribute1.addItem(attribute1Values[i]+" :: "+attribute2Values[i]);				
			}			
		}

		public void setScatterPlotAttributes(ArrayList<String> attributeList) {
			// TODO Auto-generated method stub
			sctrPlotAttribList = new ArrayList<String>();
			sctrPlotAttribList = attributeList;
		//	displayButtonHandler.setScatterPlotAttributes(attributeList);
		}
}
	 
 
